package com.yellow.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.yellow.constant.MessageConstant;
import com.yellow.constant.RedisMessageConstant;
import com.yellow.enity.Result;
import com.yellow.pojo.Order;
import com.yellow.service.OrderService;
import com.yellow.utils.AliyunSMSUtis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map) {
        //获取redis中的验证码，对比用户提交的验证码
        String telephone = (String) map.get("telephone");
        String code_sub = (String) map.get("validateCode");
        String code_server = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (code_sub != null && code_server != null && code_server.equals(code_sub)) {
            //验证码正确
            //设置预约类型
            map.put("orderType", Order.ORDERTYPE_WEIXIN);//设置为微信预约
            //调用dubbo预约
            Result result = null;
            try {
                result = orderService.order(map);
            } catch (Exception e) {
                e.printStackTrace();
                //预约失败，调用服务失败
                return null;
            }
            if (result.isFlag()) {
                //预约成功，短信
                try {
                    //AliyunSMSUtis.SendSMS(AliyunSMSUtis.ORDER_NOTICE, telephone, (String) map.get("orderDate"));
                    System.out.println("发送手机号码为 ---> " + telephone + "体检时间为---->" + (String) map.get("orderDate"));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return result;
        } else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    @RequestMapping("/findById")
    public Result findById(int id) {
        try {
            Map map = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }

}
